﻿using System;
using System.Net;
using System.Linq;
using Daemon.Model;
using Microsoft.AspNetCore.Mvc;
using Daemon.Repository.Contract;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Daemon.Common;
using Newtonsoft.Json;
using Daemon.Common.WxHelper;
using System.Threading.Tasks;

namespace DaemonAPI
{
    [ApiController]
    [Route("daemonApi/[controller]/[action]")]
    public class WxLoginController : BaseApiController<WxConfig, IWxConfigRepository>
    {
        private readonly ApiDBContent _context;
        private readonly IWxApiService _wxApiService;
        public WxLoginController(IWxConfigRepository repository,
        IHttpContextAccessor httpContextAccessor,
        IWxApiService wxApiService,
        ApiDBContent context) : base(repository, httpContextAccessor)
        {
            _context = context;
            _wxApiService = wxApiService;
        }

        [HttpGet]
        [Route("")]
        public string WxAuth(string echoStr, string signature, string timestamp, string nonce)
        {
            Console.WriteLine(echoStr);
            Console.WriteLine(signature);
            System.Console.WriteLine(timestamp);
            Console.WriteLine(nonce);
            var wxConfig = _repository.Find();
            if (WxHelper.CheckSignature(wxConfig.WxToken, signature, timestamp, nonce) && !string.IsNullOrEmpty(echoStr))
            {
                return echoStr;
            }

            return string.Empty;
        }

        [HttpGet]
        [Route("")]
        public async Task<ResultModel> WebLogin(string code)
        {
            var wxConfig = _repository.Find();
            var authResult = await _wxApiService.PublicCodeAuth(wxConfig.PublicAppId, wxConfig.PublicSecret, code);
            var userInfo = await _wxApiService.PublicUserInfo(authResult.access_token, authResult.openid);
            return new ResultModel(HttpStatusCode.OK, "", authResult);
        }
    }
}
